package eppic.pkg;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SimpleCursorAdapter;


public class CreateProjectActivity extends Activity {

	public  ClientSpinnerListener clientSelected = new ClientSpinnerListener();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.createproject);
        
        //Do Spinner
        DatabaseHelper dbHelper = new DatabaseHelper(this);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c=db.rawQuery("SELECT _id, company_name FROM clients", null);
        
        String[] from = new String[]{"company_name", "_id"};
        int[] to = new int[]{android.R.id.text1};
        
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
        adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );

        Spinner clientList = (Spinner) findViewById(R.id.client_id);
        clientList.setAdapter(adapter);
        clientList.setOnItemSelectedListener(clientSelected);
        
        
        //Do Rate
        EditText rate = (EditText) findViewById(R.id.rate);
        rate.setText("$0.00");
        rateTextWatcher rateWatcher = new rateTextWatcher(this, rate);
        rate.addTextChangedListener(rateWatcher);
    }
    
    public void submitProject(View view)
    {
    	//name
    	String name = ((EditText) findViewById(R.id.projectname)).getText().toString();
    	
    	//rate
    	int string_start = 0;
    	String rate_string = ((EditText) findViewById(R.id.rate)).getText().toString();
    	if(rate_string.substring(0,1).equals("$"))
    		string_start = 1;
    	float rate = new Float(rate_string.substring(string_start, rate_string.length()));
    	
    	//client_id
    	int client_id =  clientSelected.client_id;
    	
    	Project project = new Project(name, client_id, rate);
    	
    	if(project.save(getApplicationContext()))
    	{
    		Toast.makeText(getApplicationContext(), "Project Saved", Toast.LENGTH_SHORT).show();
    		finish();
    	}
    	else
    	{
    		Toast.makeText(getApplicationContext(), "Failed to Save Project. Try Again.", Toast.LENGTH_SHORT).show();
    	}

    	
    }
    
    public void goBack(View view) {
    	finish();
    }

    
}